<template>
  <div class="contract-relevance-container">
    <RelatedContractTable
      ref="relatedContractTable"
      v-model="list"
      :list-setting="listSetting"
      :tip-text="tipText"
      :section-title="sectionTitle"
      is-edit
      can-empty
      style="margin-bottom: 32px"
      @addRow="addContractRow"
      @selectContract="openSelectContract"
      @selectChange="selectChange"
      @scrollSelectChange="scrollSelectChange"
    />
    <!-- 关联合同弹窗 -->
    <RelatedContract
      ref="showRelatedContract"
      :has-contract-code="true"
      :is-show-other="true"
      :visible.sync="showRelatedContract"
      :expand-params="expandParams"
      @confirmRelatedContract="confirmRelatedContract"
    />
  </div>
</template>

<script>
import { mapState } from 'vuex';
import RelatedContract from '@/components/CreateOrder/relatedContract';
import RelatedContractTable from '@/components/SupplierComponent/relatedContractTable';
import { getDepartmentAll } from '@/api/config';
import { getUserList } from '@/api/user';
import { decrypt } from '@/utils';
import { getFirstDepartment } from '@/utils/index';

export default {
  name: 'ContractRelevance',
  components: {
    RelatedContract,
    RelatedContractTable
  },
  model: {
    prop: 'contractList',
    event: 'change'
  },
  props: {
    contractList: {
      type: Array,
      default: () => []
    },
    sectionTitle: {
      type: String,
      default: '合同信息'
    }
  },
  data() {
    return {
      deptTreeList: [],
      showRelatedContract: false,
      expandParams: null
    };
  },
  computed: {
    ...mapState({
      'userInfo': state => state.user.userInfo
    }),
    list: {
      get() {
        if (this.contractList && this.contractList.length) {
          return this.contractList.map(item => {
            item.contractCode = item.contractNum;
            item.contractName = item.projectName;
            item.id && (item.disable = true);
            return item;
          });
        }
        return this.contractList || [];
      },
      set(val) {
        this.$emit('change', val);
      }
    },
    tipText() {
      return `若此合同为补充合同/解约协议/年框项下订单或修改先前合作条件的，请在关联合同编号处填下之前已经审批归档的相关流程。`;
    },
    listSetting() {
      return [
        { label: '项目名称', width: '240px', type: 'inputText', isRequired: false, keyword: 'projectName', maxlength: 16 },
        { label: '合同编号', type: 'inputText', width: '200px', isRequired: true, keyword: 'contractNum', maxlength: 50 },
        { label: '合同类型', type: 'select', isRequired: false, width: '180px', keyword: 'contractType', options: [
          { id: 2, name: '推广销售类' },
          { id: 3, name: '渠道采买类' },
          { id: 4, name: 'IP商业授权类' },
          { id: 1, name: '一般购销/委托服务类' },
          { id: 5, name: '合同/kol/直播类' },
          { id: 6, name: '机构/平台合作类' },
          { id: 7, name: '电商产品购销类' },
          { id: 8, name: '投资类' },
          { id: 9, name: '其他类' }
        ] },
        { label: '申请人', type: 'scrollSelect', keyName: 'id', labelName: 'userName', renderKeyword: 'userName', isRequired: false, keyword: 'proposerName', loadmoreMethod: getUserList, notShowClear: false },
        { label: '申请人部门', type: 'cascader', width: '150px', keyword: 'proposerDepartment', showAllLevels: false, emitPath: false, checkStrictly: true, isRequired: false, keyName: 'id', labelName: 'name', options: this.deptTreeList, notShowClear: false }
      ];
    }
  },
  created() {
    const legalId = decrypt(this.$route.params.id);
    if (legalId) {
      this.expandParams = { excludeIds: legalId };
    }
    this.queryDeptTreeList();
  },
  methods: {
    // 获取部门
    queryDeptTreeList() {
      getDepartmentAll().then(res => {
        this.deptTreeList = (res && res.data) || [];
      }).then(() => {
        this.contractListFormat();
      }).catch(e => {
        console.log(e);
      });
    },
    contractListFormat() {
      if (this.list && this.list.length) {
        const res = this.list.map(it => ({
          ...it,
          creator: it.creator || this.userInfo.userName
        }));
        this.$set(this, 'list', res);
      }
    },
    // 关联合同新增一行
    addContractRow() {
      const { id, userName, departmentAry } = this.userInfo;
      // 申请人、申请部门默认取当前用户的
      const temp = [...this.list];
      temp.push({
        contractName: '',
        contractCode: '',
        contractNum: '',
        projectName: '',
        proposer: id,
        proposerName: userName,
        proposerDepartment: getFirstDepartment(departmentAry),
        proposerDepartmentName: '',
        contractSourceType: 0,
        userName
      });
      const res = temp.filter(it => !it.hasOwnProperty('orderPrivateId'));
      this.$set(this, 'list', res);
    },
    selectChange(data) {
      if (data.key === 'proposerName' && !data.item.proposerName) {
        const index = data.rowIndex;
        this.$set(this.contractList[index], 'proposerDepartment', '');
      }
    },
    scrollSelectChange(keyword, data, rowIndex) {
      const index = rowIndex;
      if (keyword === 'proposerName') {
        this.$set(this.contractList[index], 'proposerDepartment', data.departmentAry ? getFirstDepartment(data.departmentAry) : '');
      }
    },
    // 合同关联
    confirmRelatedContract(data) {
      const temp = this.list.filter(item => !item.id || (item.id && data.some(_item => _item.id === item.id)));
      const ids = temp.map(it => it.id);
      data.map(it => {
        if (!ids.includes(it.id)) {
          temp.push({
            ...it,
            disable: true,
            contractNum: it.contractCode,
            projectName: it.contractName,
            contractSourceType: 1,
            userName: it.proposer,
            proposerName: it.proposer,
            proposer: it.proposerId,
            proposerDepartment: it.proposerDepartment,
            proposerDepartmentName: it.department
          });
        }
      });
      this.$set(this, 'list', temp);
      this.showRelatedContract = false;
    },
    openSelectContract() {
      this.contractListFormat();
      this.showRelatedContract = true;
      this.$refs['showRelatedContract'].init();
      let result = [];
      if (this.list && this.list.length) {
        result = this.list.filter(it => it.contractSourceType === 1);
      }
      this.$refs['showRelatedContract'].initSelectData(result);
    }
  }
};
</script>

<style scoped lang="scss">
.contract-relevance-container {
 ::v-deep .header-box {
   margin-top: 8px;
 }
}
</style>
